package com.beifu.manager.service.assetin.impl;

import java.util.*;


import com.beifu.manager.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.beifu.manager.api.domain.spares.AssetInRfId;
import com.beifu.manager.api.domain.spares.AssetInUploadInfo;
import com.beifu.manager.dao.AssetBaseMapper;
import com.beifu.manager.dao.AssetInMapper;
import com.beifu.manager.dao.AssetInPlanMapper;
import com.beifu.manager.dao.AssetInTruthMapper;
import com.beifu.manager.dao.AssetInfoMapper;
import com.beifu.manager.dao.AssetModelMapper;
import com.beifu.manager.dao.AssetTypeMapper;
import com.beifu.manager.dao.OrganizerMapper;
import com.beifu.manager.dao.RoleMapper;
import com.beifu.manager.dao.UserInfoMapper;
import com.beifu.manager.service.assetin.AssetInService;
import com.utils.Constants.ASSET_INFO_STATUS;
import com.utils.PageUtils;

/**
 * 
* Title: RoleServiceImpl
* Description:
* @author    BaiBing
* @date      2018年6月10日
 */
@Service
public class AssetInServiceImpl implements AssetInService {

	private static final Logger logger = LoggerFactory.getLogger(AssetInServiceImpl.class);

	@Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private AssetInMapper assetInMapper;
    
    @Autowired
    private AssetInPlanMapper assetInPlanMapper;
    
    @Autowired
    private UserInfoMapper userInfoMapper;
    
    @Autowired
    private OrganizerMapper organizerMapper ;
    
    @Autowired
    private AssetInTruthMapper assetInTruthMapper;
    
    @Autowired
    private AssetBaseMapper assetBaseMapper;
    
    @Autowired
    private AssetInfoMapper assetInfoMapper;
    
    @Autowired
    private AssetTypeMapper assetTypeMapper;
    
    @Autowired
    private AssetModelMapper assetModelMapper;
    
    
    @Override
    public PageUtils getAssetInPage(PageUtils page){
    	 AssetInExample example = (AssetInExample) page.getQueryParames();
    	 List<AssetIn> list = assetInMapper.getAssetInPage((page.getPage()-1)*page.getLimit(),page.getLimit(), example);
    	 int count = assetInMapper.countByExample(example);
         page.setList(list);
         page.setCountNum(count);
         return page;
	}

    
    @Override
    public void createAsstInOrder(String userId, String organizeId,
			String create_inTime, String status,
			List<String> assetTypeSelectArr,List<String> assetModelSelectArr,
			List<String> assetTypeNumArr,String create_remark,String vender){
    	//保存备品入库单
    	AssetIn assetIn = new AssetIn();
    	assetIn.setCreateTime(new Date());
    	assetIn.setCreateUserId(Integer.valueOf(userId));
    	assetIn.setSrcOrganizeId(Integer.valueOf(vender));
    	assetIn.setDestOrganizeId(Integer.valueOf(organizeId));
    	assetIn.setInTime(com.mds.manager.utils.DateUtils.stringToDate(create_inTime, "yyyy-MM-dd"));
    	assetIn.setStatus(Integer.valueOf(status));
    	assetIn.setRemark1(create_remark);
    	assetInMapper.insertAndGetId(assetIn);
    	Long assetInId =  assetIn.getId();
    	//保存备品入库单类型列表
    	for(int i=0;i<assetTypeSelectArr.size();i++){
    		String assetType = assetTypeSelectArr.get(i);
    		String assetModel  = assetModelSelectArr.get(i);
    		String assetTypeNum = assetTypeNumArr.get(i);
    		AssetInPlan assetInPlan = new AssetInPlan();
    		assetInPlan.setAssetInId(assetInId);
    		assetInPlan.setInCount(Integer.valueOf(assetTypeNum));
    		assetInPlan.setAssetTypeId(Integer.valueOf(assetType));
    		assetInPlan.setAssetModelId(Integer.valueOf(assetModel));
    		assetInPlanMapper.insert(assetInPlan);
    	}
    }
   
    @Override
    public AssetIn getAssetInById(Integer valueOf){
    	return assetInMapper.selectByAssetInId(Long.valueOf(valueOf));
    }

    private Map<String,String > checkUploadRfIdsRepeat(String assetInId,List<AssetInUploadInfo> assetsInList){
    	Map<String,String > checkResult = new HashMap<String, String>();
    	Set<AssetInRfId> rfIdsAll = new HashSet<AssetInRfId>();
    	if(null != assetsInList && assetsInList.size()>0){
			for(AssetInUploadInfo assetInUploadInfo : assetsInList){
				if(null != assetInUploadInfo.getRfIds()){
					rfIdsAll.addAll(assetInUploadInfo.getRfIds());
				}
			}
		}

		if(rfIdsAll.size() > 0){
			logger.info("备品入库单编号：{"+assetInId+"}，去重后rfId总数量为:{"+rfIdsAll.size()+"}");
			for(AssetInRfId assetInRfId :rfIdsAll){
				AssetInTruthExample assetInTruthExample = new AssetInTruthExample();
				assetInTruthExample.createCriteria().andAssetInfoRfidCodeEqualTo(assetInRfId.getRfId());
				List<AssetInTruth> checkAssetInTruthResult = assetInTruthMapper.selectByExample(assetInTruthExample);
				if(null != checkAssetInTruthResult && checkAssetInTruthResult.size() > 0){
					checkResult.put("result","false");
					checkResult.put("msg","已存在rfId:"+assetInRfId.getRfId()+"的备品数据");
					return checkResult;
				}
			}
		}
		checkResult.put("result","true");
    	return checkResult;
	}

    @Override
    public Map<String, String> saveAssetInTruth(Map<String, Object> paramMap){
    	Map<String,String> resultMap = new HashMap<String,String>();
    	String assetInId = (String)paramMap.get("assetInId");//备品入库单编号
    	List<AssetInUploadInfo> assetsInList = (List<AssetInUploadInfo>) paramMap.get("assetsInList");//备品上传列表
    	String operatingUserId = (String)paramMap.get("operatingUserId");//操作员编号
    	String operatingDeviceId = (String)paramMap.get("operatingDeviceId");//设备编号

		//检查上送的备品列表是否已存在
		Map<String,String> checkResult = checkUploadRfIdsRepeat(assetInId,assetsInList);
		String result = checkResult.get("result");
        String msg = checkResult.get("msg");
		if("false".equals(result)){
			logger.error("检查备品入库上传列表数据结果失败："+msg);
			throw new RuntimeException(msg);
		}

    	//查询备品入库信息
    	AssetIn assetIn = assetInMapper.selectByPrimaryKey(Long.valueOf(assetInId));
    	//查询用户信息
    	UserInfo userInfo = userInfoMapper.selectByPrimaryKey(Integer.valueOf(operatingUserId));
    	//查询组织信息
    	Organizer organizer = organizerMapper.selectByPrimaryKey(userInfo.getOrganizeId());
    	
    	Date inDate = new Date();
    	
    	Map<String,AssetInPlan> assetInPlanMap = new HashMap<String,AssetInPlan>();
    	Map<String,AssetType> assetTypeMap = new HashMap<String,AssetType>();
    	Map<String,AssetModel> assetModelMap = new HashMap<String,AssetModel>();
    	
    	List<AssetInTruth> assetInTruthList = new ArrayList<AssetInTruth>();
    	List<AssetInfo> assetInfoList = new ArrayList<AssetInfo>();
    	
    	for(AssetInUploadInfo assetInUploadInfo:assetsInList){
    		String assetInPlanId = assetInUploadInfo.getAssetInPlanId();//备品入库计划Id
    		List<AssetInRfId> rfIdList = assetInUploadInfo.getRfIds();//备品入库rfIds列表
    		
    		AssetInPlan assetInPlan = null;
    		AssetType assetType = null;
    		AssetModel assetModel = null;
    		
    		if(!assetInPlanMap.containsKey(assetInPlanId)){
    			assetInPlan = assetInPlanMapper.selectByPrimaryKey(Long.valueOf(assetInPlanId));
    			assetInPlanMap.put(assetInPlanId, assetInPlan);
    		}else{
    			assetInPlan = assetInPlanMap.get(assetInPlanId);
    		}
    		
    		if(!assetTypeMap.containsKey(assetInPlan.getAssetTypeId()+"")){
    			assetType = assetTypeMapper.selectByPrimaryKey(assetInPlan.getAssetTypeId());
    			assetTypeMap.put(assetInPlan.getAssetTypeId()+"", assetType);
    		}else{
    			assetType = assetTypeMap.get(assetInPlan.getAssetTypeId()+"");
    		}
    		
    		if(!assetModelMap.containsKey(assetInPlan.getAssetModelId()+"")){
    	    	assetModel = assetModelMapper.selectByPrimaryKey(assetInPlan.getAssetModelId());
    	    	assetModelMap.put(assetInPlan.getAssetModelId()+"", assetModel);
    		}else{
    			assetModel = assetModelMap.get(assetInPlan.getAssetModelId()+"");
    		}
    		
    		for(AssetInRfId assetInRfId:rfIdList){
    			AssetInTruth assetInTruth = getAssetInTruth(assetInRfId.getRfId(),organizer.getOrganizeAddress(),
    												operatingUserId,operatingDeviceId,assetInId,inDate);
    			assetInTruthList.add(assetInTruth);
    			
    			AssetBase assetBase = getAssetBase(assetInPlan.getAssetTypeId(),assetType,assetModel);
        		assetBaseMapper.insertById(assetBase);
        		
        		Integer assetBaseId = assetBase.getId();
        		//保存asset_info
        		AssetInfo assetInfo = getAssetInfo(assetBaseId,assetInRfId.getRfId(),organizer.getId(),organizer.getOrganizeAddress(),assetIn);
        		assetInfoList.add(assetInfo);
    		}
    	}
    	
    	//保存备品入库AssetInTruth
    	assetInTruthMapper.insertBatch(assetInTruthList);
    	//保存备品入库AssetInfo
    	assetInfoMapper.insertBatch(assetInfoList);
    	assetIn.setStatus(1);
    	assetInMapper.updateByPrimaryKeySelective(assetIn);
    	return resultMap;
    }
    
    private AssetInfo getAssetInfo(Integer assetBaseId,String rfId,
    						Integer currentOrganizerId,String currPosition,AssetIn assetIn){
    	AssetInfo assetInfo = new AssetInfo();
    	assetInfo.setAssetBaseid(assetBaseId);
    	assetInfo.setRfidCode(rfId);
    	assetInfo.setVenderId(assetIn.getSrcOrganizeId());// TODO 供应商ID，目前没有获取到
    	assetInfo.setCurrentOrganizerId(currentOrganizerId);//资源当前所在组织
    	assetInfo.setStatus(Integer.valueOf(ASSET_INFO_STATUS.Inlibrary.getStatus()));//在车
    	assetInfo.setCurrentPostion(currPosition);//资源当前所在位置
    	assetInfo.setWashNum(0);//洗涤次数
    	assetInfo.setIsScrap("0");//未报废
    	return assetInfo;
    }
    
    private AssetBase getAssetBase(Integer assetTypeId,AssetType assetType,AssetModel assetModel){
    	AssetBase assetBase = new AssetBase ();
    	assetBase.setAssetName(assetType.getName());//TODO 资产名称，没有获取到
    	//assetBase.setAssetUnit(assetUnit);TODO 计量单位，没有获取到
    	assetBase.setAssetModel(assetModel.getAssetModelName());//TODO 资产型号，没有获取到
    	assetBase.setAssetTypeId(assetTypeId);
    	assetBase.setAssetModelId(assetModel.getId());//TODO 资产型号ID，没有获取到
    	return assetBase;
    }
    
    private AssetInTruth getAssetInTruth(String rfId,String address,String operatingUserId,
    															String operatingDeviceId,String assetInId,Date inDate){
    	AssetInTruth assetInTruth = new AssetInTruth();
    	assetInTruth.setAssetInfoRfidCode(rfId);
    	assetInTruth.setInPotion(address);
    	assetInTruth.setOperatingUserId(Integer.valueOf(operatingUserId));
    	assetInTruth.setOperatingDeviceId(operatingDeviceId);
    	assetInTruth.setAssetInId(Long.valueOf(assetInId));
    	assetInTruth.setInputTime(inDate);
    	return assetInTruth;
    }
    
    @Override
    public void batchDelAssetIn(String[] ids){
    	assetInMapper.batchDelAssetIn(ids);
    }

	public static void main(String[] args) {
		/*Set<String> test = new HashSet<String>();
		test.add("1");
		test.add("2");
		test.add("1");
		test.add("2");
		test.add("3");
		System.out.println("args = [" + test.size() + "aaa]");
		for(String s : test){
			System.out.println("args = [" + s + "]");
		}*/
		Set<AssetInRfId> test = new HashSet<AssetInRfId>();
		AssetInRfId a = new AssetInRfId();a.setRfId("123");
		AssetInRfId b = new AssetInRfId();b.setRfId("123");
		AssetInRfId c = new AssetInRfId();c.setRfId("1234");
		AssetInRfId d = new AssetInRfId();d.setRfId("1234");
		AssetInRfId e = new AssetInRfId();e.setRfId("12345");
		test.add(a);
		test.add(b);
		test.add(c);
		test.add(d);
		test.add(e);
		for(AssetInRfId l:test){
			System.out.println("args = [" + l.getRfId() + "]");
		}
	}
}
